package com.dingreading.cloud.admin.service.impl;

import com.dingreading.cloud.admin.entity.TimeTasks;
import com.dingreading.cloud.admin.entity.table.TimeTasksTableDef;
import com.dingreading.cloud.admin.mapper.TimeTasksMapper;
import com.dingreading.cloud.admin.service.TimeTasksService;
import com.dingreading.cloud.common.util.DateUtil;
import com.dingreading.cloud.common.util.PageUtil;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryCondition;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.core.update.UpdateChain;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * 服务层实现。
 *
 * @author Administrator
 * @since 2024-07-31
 */
@Service
public class TimeTasksServiceImpl extends BaseServiceImpl<TimeTasksMapper, TimeTasks, TimeTasksTableDef> implements TimeTasksService {

    @Override
    protected TimeTasksTableDef getTable() {
        return TimeTasksTableDef.timeTasks;
    }

    @Override
    public Page<TimeTasks> pageList(PageUtil pageUtil, String keyword, Integer enabled) {
        QueryCondition condition = QueryCondition.createEmpty();
        if (StringUtils.isNotBlank(keyword))
            condition.and(table.corpName.like(keyword)
                    .or(table.typeName.like(keyword))
                    .or(table.intro.like(keyword))
            );
        if (enabled != null)
            condition.and(table.enabled.eq(enabled));

        QueryWrapper wrapper = QueryWrapper.create()
                .where(condition)
                .orderBy(table.enabled.desc(), table.expireTime.asc());

        return getMapper().paginate(Page.of(pageUtil.getPage(), pageUtil.getRows()), wrapper);
    }

    @Override
    public List<TimeTasks> getExpireTask(int day) {
        QueryCondition condition = QueryCondition.createEmpty();
        condition.and(table.enabled.eq(1));
        // 当天日期 + "23:59:59"
        Date date = DateUtil.getEndTime();
        // 即将到期的日期，列如，当天日期加上10天
        Date addDays = DateUtil.addDays(date, day);
        condition.and(table.expireTime.between(date, addDays));

        return getMapper().selectListByCondition(condition);
    }

    @Override
    public boolean updateEnabled(Long id, Integer enabled) {
        return UpdateChain.of(TimeTasks.class)
                .set(table.enabled, enabled)
                .where(table.id.eq(id))
                .update();
    }
}